package com.example.sendmassege.scoket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author wxc
 * @date 2021年04月30日 11:08
 */
public class TcpServerDemo {
    public static void main(String[] args) {
        ByteArrayOutputStream baos=null;
        ServerSocket serverSocket=null;
        Socket accept=null;
        InputStream inputStream=null;
        try {
            //1.我有一个端口号
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接
            accept = serverSocket.accept();
            //3.读取客户端的消息
            inputStream = accept.getInputStream();
            //管道流
            baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len=inputStream.read(bytes))!=-1){
                baos.write(bytes,0,len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭原则：先开后关
            try {
                baos.close();
                inputStream.close();
                accept.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
